package com.xinjie.www.service.post;

import com.xinjie.www.dao.BaseDao;
import com.xinjie.www.dao.post.PostDao;
import com.xinjie.www.dao.post.PostDaoImpl;
import com.xinjie.www.po.Post;

import java.sql.Connection;
import java.sql.Date;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class PostServiceImpl implements PostService {
    private final PostDao postDao;

    public PostServiceImpl() {
        postDao = new PostDaoImpl();
    }

    @Override
    public boolean writePost(String title, String tieba, String time, String content, String writer) throws SQLException, ClassNotFoundException {
        Connection conn = null;
        boolean flag = false;
        conn = BaseDao.getConnection();
        if (postDao.writePost(conn, title, tieba, time, content, writer) > 0) {
            flag = true;
        }
        BaseDao.closeResource(conn, null, null);

        return flag;
    }

    @Override
    public List<Post> getOwnPost(String writer) throws SQLException, ClassNotFoundException {
        Connection conn = null;
        List<Post> post = new ArrayList<>();
        conn = BaseDao.getConnection();
        post = postDao.getOwnPost(conn, writer);
        BaseDao.closeResource(conn, null, null);
        return post;
    }

    @Override
    public List<Post> getAllPost(String managerName) throws SQLException, ClassNotFoundException {
        Connection conn = null;
        List<Post> post = new ArrayList<>();
        conn = BaseDao.getConnection();
        post = postDao.getAllPost(conn, managerName);
        BaseDao.closeResource(conn, null, null);
        return post;
    }

    @Override
    public boolean deletePost(int id, String tieba) throws SQLException, ClassNotFoundException {
        Connection conn = null;
        boolean flag = false;
        conn=BaseDao.getConnection();
        if (conn!=null){
            if (postDao.deletePost(conn, id, tieba) > 0) {
                flag = true;
            }
        }
        BaseDao.closeResource(conn, null, null);
        return flag;
    }

    @Override
    public List<Post> getPostList(String tieba) throws SQLException, ClassNotFoundException {
        Connection conn = null;
        List<Post> posts = new ArrayList<>();
        conn = BaseDao.getConnection();
        posts = postDao.getPostList(conn, tieba);
        BaseDao.closeResource(conn, null, null);
        return posts;
    }

    @Override
    public Post getPost(int postId) throws SQLException, ClassNotFoundException {
        Connection conn = null;
        conn = BaseDao.getConnection();
        Post post = new Post();
        if (conn!=null){
            post = postDao.getPost(conn, postId);
            BaseDao.closeResource(conn,null,null);
        }
        return post;
    }
}
